// functionPage/pages/minePage/myExperience/myExperience.js
import throttle from '../../../../utils/throttle.js';
import { hasPermission } from '../../../../utils/tools';
import Http from '../../../../utils/http.js';
const http = new Http();
const app = getApp();

Page({
    /**
     * 页面的初始数据
     */
    data: {
        idItem: '', //经验id
        pageNum: 0,
        loading: true,
        loadingAll: false,
        experienceArr: [],
        activeExpIndex: null, // 当前经验索引
        total: 0,
        //操作弹框
        show: false,
        activeCreateUid: '',
        showNext: false,
        permissionList: ['00', '01'],
        lastest: {
            review_title: '暂无消息',
        }, // 最近第一条审核消息
        unreadCount: 0, // 未读消息数
        showNewBox: true, //产看他人主页隐藏消息提示
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            showNewBox: !options.uid,
        });
        if (options.uid) {
            this.getExperienceList(options.uid);
        } else {
            this.getExperienceList();
        }
    },

    onShow: function () {
        this.getLatestVerifyMsg();
    },

    // 刷新
    refresh() {
        this.setData({
            pageNum: 0,
            loading: true,
            loadingAll: false,
            experienceArr: [],
        });
        this.getExperienceList();
    },

    getExperienceList(uid) {
        if (!this.data.loadingAll) {
            this.setData({
                pageNum: this.data.pageNum + 1,
                loading: true,
                loadingAll: false,
            });
            let data = {
                authId: app.globalData.authId,
                pageNo: this.data.pageNum,
                pageSize: 20,
                createuid: uid || app.globalData.uid,
            };
            http.getRequest(`cjMap/getExperienceList`, data).then((res) => {
                if (res.status == 0) {
                    if (res.data.length) {
                        for (let i = 0; i < res.data.length; i++) {
                            res.data[i].createtime = app.timeago(
                                res.data[i].createtime
                            );
                            res.data[i].ellipsis =
                                res.data[i].content.length > 168;
                            this.data.experienceArr.push(res.data[i]);
                        }
                    }
                    this.setData(
                        {
                            experienceArr: this.data.experienceArr,
                            loading: false,
                            total: res.pager.totalRows,
                        },
                        () => {
                            if (uid) {
                                wx.setNavigationBarTitle({
                                    title: `经验·${this.data.total}`,
                                });
                            } else {
                                wx.setNavigationBarTitle({
                                    title: `我的经验·${this.data.total}`,
                                });
                            }
                        }
                    );

                    if (res.pager.currentPage >= res.pager.totalPages) {
                        this.setData({
                            loadingAll: true,
                        });
                    }
                } else {
                    this.setData({
                        loadingAll: true,
                        loading: false,
                    });
                }
            });
        }
    },

    changeNav: throttle(
        (e) => {
            let { nav } = e.currentTarget.dataset;
            console.log(nav);
            wx.navigateTo({
                url: `${nav}`,
            });
        },
        200,
        {
            trailing: false,
        }
    ),
    // 编辑功能
    edit(e) {
        let { uid, id, excellentflg, index, authority } = e.detail;

        let actions = [
            {
                name: '编辑',
                color: '#333333',
                id: 2,
            },
            {
                name: '删除',
                color: '#FF455E',
                id: 1,
            },
        ];

        if (hasPermission(this.data.permissionList) || authority) {
            if (excellentflg === '00') {
                actions.splice(0, 0, {
                    name: '设置为精华',
                    color: '#333333',
                    id: 3,
                });
            } else {
                actions.splice(0, 0, {
                    name: '取消精华',
                    color: '#333333',
                    id: 4,
                });
            }

            actions.splice(2, 0, {
                name: '转移至',
                color: '#333333',
                id: 5,
            });
        }

        this.setData({
            show: true,
            activeCreateUid: uid,
            idItem: id,
            actions,
            activeExpIndex: index,
        });
    },

    onSelect(e) {
        let _that = this;
        if (e.detail.id == 2) {
            wx.navigateTo({
                url: `../../../../releasePage/pages/addExperience/addExperience?type=01&id=${_that.data.idItem}&current=1`,
            });
        } else if (e.detail.id == 1) {
            wx.showModal({
                title: '提示',
                content: '确认要删除该项吗？',
                success: function (res) {
                    if (res.confirm) {
                        _that.deleteExperience();
                    } else {
                        console.log('点击取消回调');
                    }
                },
            });
        } else if (e.detail.id == 3) {
            _that.setExperienceExcellent('01');
        } else if (e.detail.id == 4) {
            _that.setExperienceExcellent('00');
        } else if (e.detail.id == 5) {
            _that.setData({
                showNext: true,
            });
        }
        _that.setData({
            show: false,
        });
    },
    // 预览图片
    previewImage(e) {
        let index = e.currentTarget.dataset.index;
        let images = e.currentTarget.dataset.images;
        wx.previewImage({
            current: images[index],
            urls: images,
        });
    },

    //取消
    onCancel(e) {
        this.setData({
            show: false,
        });
    },

    // 删除经验
    deleteExperience() {
        let _that = this;
        wx.request({
            url: app.globalData.rootPath + `cjMap/deleteExperience`,
            method: 'GET',
            header: {
                'content-type': 'application/x-www-form-urlencoded',
            },
            data: {
                authId: app.globalData.authId,
                id: _that.data.idItem,
            },
            success: function (res) {
                if (res.data.status === '0') {
                    wx.showToast({
                        title: '删除成功',
                        icon: 'success',
                        duration: 2000,
                    });
                    _that.hiddenListItem(
                        'experienceArr',
                        _that.data.activeExpIndex
                    );
                    let pages = getCurrentPages(); //当前页面栈
                    let prevPage = pages[pages.length - 2]; //上一页面
                    let prevPage2 = pages[pages.length - 3]; //上一页面
                    prevPage.refresh();
                    if (prevPage2 && typeof prevPage2.refresh == 'function') {
                        try {
                            prevPage2.refresh();
                        } catch (err) {
                            return;
                        }
                    }
                }
            },
        });
    },

    // 设为精华和取消精华
    setExperienceExcellent(excellentflg) {
        let _that = this;
        wx.request({
            url:
                app.globalData.rootPath +
                `cjMap/setExperienceExcellent?authId=${app.globalData.authId}`,
            header: {
                'content-type': 'application/json',
            },
            data: {
                excellentflg,
                id: _that.data.idItem,
            },
            success: function (res) {
                if (res.data.status == '0') {
                    _that.setData({
                        [`experienceArr[${_that.data.activeExpIndex}].excellentflg`]: excellentflg,
                    });
                    _that.onCancel();

                    app.globalData.expRefresh = true;

                    let pages = getCurrentPages(); //当前页面栈

                    let prevPage = pages[pages.length - 2];
                    if (prevPage && typeof prevPage.refresh == 'function') {
                        prevPage.refresh();
                    }

                    let prevPage2 = pages[pages.length - 3];
                    if (prevPage2 && typeof prevPage2.refresh == 'function') {
                        prevPage2.refresh();
                    }

                    let prevPage3 = pages[pages.length - 4];
                    if (prevPage3 && typeof prevPage3.refresh == 'function') {
                        prevPage3.refresh();
                    }
                }
            },
        });
    },

    changeNav: throttle(
        (e) => {
            let { nav } = e.currentTarget.dataset;
            console.log(nav);
            wx.navigateTo({
                url: `${nav}`,
            });
        },
        200,
        {
            trailing: false,
        }
    ),

    // 删除经验时，前端先隐藏这条经验而不是直接刷新
    hiddenListItem(arrName, index) {
        this.data[arrName].splice(index, 1);
        this.setData({
            [arrName]: this.data[arrName],
        });
    },

    // 处理点赞同步问题
    handleLike(e) {
        let { id, praiseflg, praisecnt } = e.detail;
        let expIndex = -1;
        this.data.experienceArr.map((item, index) => {
            if (item.id === id) {
                expIndex = index;
            }
        });
        if (expIndex > -1) {
            this.setData({
                [`experienceArr[${expIndex}].praiseflg`]: praiseflg,
                [`experienceArr[${expIndex}].praisecnt`]: praisecnt,
            });
        }
    },

    // 点击评论图标直接跳转到底部评论区
    handleComment: throttle(
        (e) => {
            const { id } = e.detail;
            wx.navigateTo({
                url: `../../experienceDetail/experienceDetail?id=${id}&comment=1`,
            });
        },
        200,
        {
            trailing: false,
        }
    ),

    // 刷新某一条经验的评论数
    refreshCommentNum(params) {
        const { id, commentcount } = params;
        const expIndex = this.data.experienceArr.findIndex((item) => {
            return item.id === id;
        });
        if (expIndex > -1) {
            this.setData({
                [`experienceArr[${expIndex}].commentcount`]: commentcount,
            });
        }
    },

    // 转移上一步
    upBtn(e) {
        this.setData({
            showNext: false,
            show: true,
        });
        this.tabbarShow();
    },

    hideTranferCover(e) {
        this.setData({
            showNext: false,
        });
    },

    // 获取最新审核消息
    getLatestVerifyMsg() {
        let data = {
            authId: app.globalData.authId,
            origintype: '05',
        };
        http.getRequest('cjMap/getLatestVerifyMsg', data).then((res) => {
            if (res.status == 0) {
                let lastest = res.data;
                if (lastest && lastest.type) {
                    // 处理审核消息标题
                    const action =
                        app.globalData.uid === lastest.originuid
                            ? '发布'
                            : '编辑';
                    if (lastest.type === '08') {
                        lastest.review_title = `您${action}的经验被审核通过`;
                    }
                    if (lastest.type === '09') {
                        lastest.review_title = `您${action}的经验因不符合要求被删除`;
                    }
                    if (lastest.type === '10') {
                        lastest.review_title = `恭喜，您${action}的经验被设置为优秀`;
                    }
                    this.setData({
                        lastest,
                    });
                }
                this.setData({
                    unreadCount: res.count,
                });
            }
        });
    },
});
